<template>
  <div>
    <div class="topBtn">
      <div class="sizeBig"><span>仓库</span></div>
      <div style="float: right;margin-right:20px">
        <el-button type="primary" @click="exportExcel" style="height:36px;width:90px;">
          <i class="iconfont icon-icon-"></i> 导出
        </el-button>
        <el-button type="primary" @click="forbidden" style="height:36px;width:90px;">
          <i class="icon-jiny"></i>禁用
        </el-button>
        <el-button type="primary" @click="Enable" style="height:36px;width:90px;">
          <i class="icon-qiy"></i>启用
        </el-button>
        <el-button type="primary" @click.native="add" style="height:36px;width:90px;">
          <i class="iconfont icon-addNew"></i> 新增
        </el-button>
        <el-button type="primary" @click="edit()" icon="el-icon-edit" style="height:36px;width:90px;">修改</el-button>
        <el-button type="primary" @click="remove" icon="el-icon-delete" style="height:36px;width:90px;">删除</el-button>
      </div>
    </div>
    <div class="message">
      <p class="character">
        维护仓库基础资料，可以按功能、区域、类型来设置不同的仓库基础资料，有了仓库ID才能做库存管理。只有对产线线边仓有精准的库存管控，才能非常精确的实现生产领料和缺料预警。
        <span
          class="skip"
        >查看帮助文档</span>
      </p>
    </div>
    <div class="inputcontent">
      <el-input v-model="search" placeholder="请输入内容" class="inSearch" @keydown.native.enter="init"></el-input>
      <div class="iconSearch"></div>
    </div>
    <div class="tablesize">
      <Table :reset="reset" v-on:getId="getListId" id="out-table" v-on:changeData="changedata"></Table>
    </div>

    <!-- 分页 -->
    <div class="block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10,20,50,100]"
        :page-size="size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="TotalNum">
      </el-pagination>
    </div>

    <!-- 新增弹出框 -->
    <el-dialog
      title="新增数据"
      :visible.sync="addDialogVisible"
      width="600px">
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="formName"
        label-width="140px"
        class="demo-ruleForm">
        <el-form-item label="仓库编码：" prop="code">
          <el-input v-model="ruleForm.code" style="width:350px"></el-input>
        </el-form-item>
        <el-form-item label="仓库名称：" prop="storeName">
          <el-input v-model="ruleForm.storeName	" style="width:350px"></el-input>
        </el-form-item>
        <el-form-item label="仓库类型：" prop="storeType">
          <el-select v-model="ruleForm.storeType" placeholder="请选择仓库类型" style="width:350px">
            <el-option
              v-for="(item,index) in options"
              :key="index"
              :label="item.label" 
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="满仓数：" prop="fullCapacity">
          <el-input v-model="ruleForm.fullCapacity" style="width:350px"></el-input>
        </el-form-item>
        <el-form-item label="是否可销售：" prop="isSale">
          <!-- <el-input v-model="ruleForm.isSale" style="width:350px"></el-input> --> 
          <el-radio-group v-model="ruleForm.isSale">
            <el-radio :label="0">不可以</el-radio>
            <el-radio :label="1">可以</el-radio>
          </el-radio-group>      
        </el-form-item>
        <el-form-item label="是否可排产：" prop="isScheduling">
          <!-- <el-input v-model="ruleForm.isScheduling" style="width:350px"></el-input> -->  
          <el-radio-group v-model="ruleForm.isScheduling">
            <el-radio :label="0">不可以</el-radio>
            <el-radio :label="1">可以</el-radio>
          </el-radio-group>      
        </el-form-item>
        <el-form-item label="是否可生产：" prop="isWork">
          <!-- <el-input v-model="ruleForm.isWork" style="width:350px"></el-input> -->
          <el-radio-group v-model="ruleForm.isWork">
            <el-radio :label="0">不可以</el-radio>
            <el-radio :label="1">可以</el-radio>
          </el-radio-group>         
        </el-form-item>
        <el-form-item>
          <el-button @click.native="addDialogVisible=false">关闭</el-button>
          <el-button type="primary" @click="submitForm('formName')">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 修改弹出框 -->
    <el-dialog
      title="修改数据"
      :visible.sync="editDialogVisible" 
      width="600px"  >
      <el-form
        :model="editInfo"
        :rules="rules"
        ref="editForm"
        label-width="140px"
        class="demo-ruleForm">
        <el-form-item label="仓库ID" prop="storeID">
          <el-input v-model="editInfo.storeID" style="width:350px" disabled></el-input>
        </el-form-item>
        <el-form-item label="仓库编码" prop="code">
          <el-input v-model="editInfo.code" style="width:350px" disabled></el-input>
        </el-form-item>
        <el-form-item label="仓库名称" prop="storeName">
          <el-input v-model="editInfo.storeName	" style="width:350px"></el-input>
        </el-form-item>
        <el-form-item label="仓库类型" prop="storeType">
          <!-- <el-input v-model="editInfo.storeType" style="width:350px"></el-input> -->
          <!-- <el-select v-model="editInfo.storeType" placeholder="请选择仓库类型"> -->
            <!-- <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.value"
              :value="item.value">{{item.label}}
            </el-option>
          </el-select> -->
          <el-select v-model="editInfo.storeType" placeholder="请选择仓库类型" style="width:350px">
            <!-- <el-option label="公司总仓" value="0"></el-option>
            <el-option label="岗位仓" value="1"></el-option>
            <el-option label="客户仓" value="2"></el-option> -->
            <el-option
              v-for="(item,index) in options"
              :key="index"
              :label="item.label" 
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="满仓数" prop="fullCapacity">
          <el-input v-model="editInfo.fullCapacity" style="width:350px"></el-input>
        </el-form-item>
        <el-form-item label="是否可销售" prop="isSale">  
          <el-radio-group v-model="editInfo.isSale">
            <el-radio :label="0">不可以</el-radio>
            <el-radio :label="1">可以</el-radio>
          </el-radio-group>       
        </el-form-item>
        <el-form-item label="是否可排产" prop="isScheduling">
          <el-radio-group v-model="editInfo.isScheduling">
            <el-radio :label="0">不可以</el-radio>
            <el-radio :label="1">可以</el-radio>
          </el-radio-group>             
        </el-form-item>
        <el-form-item label="是否可生产" prop="isWork">
          <el-radio-group v-model="editInfo.isWork">
            <el-radio :label="0">不可以</el-radio>
            <el-radio :label="1">可以</el-radio>
          </el-radio-group>             
        </el-form-item>
        <el-form-item>
          <el-button @click.native="editDialogVisible=false">关闭</el-button>
          <el-button type="primary" @click.native="editSubmitForm('editForm')">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {
  getStore,
  insertStore,
  updateStore,
  removeStore,
  startOrStopStore 
} from "@/api/warehouse";
import Table from "./components/warehouseTable";
import {delay} from '@/utils/autoSearch'
import FileSaver from "file-saver";
import XLSX from "xlsx";

export default {
  name: "warehouse",
  components: {
    Table
  },
  data() {
    return {
      options:[
        {
          value:0,
          label:'公司总仓'
        },
        {
          value:1,
          label:'岗位仓'
        },
        {
          value:2,
          label:'客户仓'
        }
      ],
      search: "",
      reset: [], //初始化數據
      
      currentPage: 1, //初始页 
      size:10,
      TotalNum: 0,//数据总条数
      
      addDialogVisible: false, //新增弹出框
      editDialogVisible:false,//修改弹出框
      checkIds: [], //勾选的id数组
      addlist: [], //勾选传过来的数据
      ruleForm: {
        code: "", //仓库编码
        storeName: "", //仓库名称
        storeType: "", //仓库类型
        fullCapacity: "", //满仓数
        isSale: "", //是否可销售
        isScheduling: "", //是否可排产
        isWork: "" //是否可生产
      },
      editInfo: {
        storeID: "",
        code: "", //仓库编码
        storeName: "", //仓库名称
        storeType: "", //仓库类型
        fullCapacity: "", //满仓数
        isSale: "", //是否可销售
        isScheduling: "", //是否可排产
        isWork: "" //是否可生产
      },
      rules: {
        code: [
          { required: true, message: "请输入仓库编码", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" }
        ],
        storeName: [
          { required: true, message: "请输入仓库名称", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" }
        ],
        storeType: [
          { required: true, message: "请输入仓库类型", trigger: "change" },
        ],
        fullCapacity: [
          { required: true, message: "请输入满仓数", trigger: "blur" },
          
        ],
        isSale: [
          { required: true, message: "请输入是否可销售", trigger: "change" },
        ],
        isScheduling: [
          { required: true, message: "请输入是否可排产", trigger: "change" },        
        ],
        isWork: [
          { required: true, message: "请输入是否可生产", trigger: "change" },         
        ]
      },     
    };
  },
  watch: {
    //用来监听页面变量的改变
    //监听搜索，300ms执行一次fetchData方法（去搜索）
    search() {
      delay(() => {
        this.fetchData();
      }, 300);
    }
  },
  mounted() {
    this.init();
  },
  methods: {
    // 自动搜索的方法
    async fetchData(val){
      this.init({keyName:this.search})
    },
    handleSizeChange(size){
      this.size = size
      getStore({ keyName:this.search,page:1,pageSize:this.size}).then(res => {
        if (parseInt(res.Code) === 1) {
          this.reset = res.Result.Items;
        }
      })
    },
    handleCurrentChange(currentPage){
      this.currentPage = currentPage
      getStore({ keyName:this.search,page:this.currentPage,pageSize:this.size}).then(res => {
        if (parseInt(res.Code) === 1) {
          this.reset = res.Result.Items;
        }
      })
    },
    //请求数据  
    init() {
      this.reset = [];
      getStore({ keyName:this.search,page:1,pageSize:10}).then(res => {
        if (parseInt(res.Code) === 1) {
          this.reset = res.Result.Items;
          this.TotalNum = res.Result.TotalNum
        }
      })
    },
    
    // 导出
    exportExcel() {
      /* generate workbook object from table */
      var xlsxParam = { raw: true }; // 导出的内容只做解析，不进行格式转换
      var wb = XLSX.utils.table_to_book(
        document.querySelector("#out-table"),
        xlsxParam
      );

      /* get binary string as output */
      var wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array"
      });
      try {
        FileSaver.saveAs(
          new Blob([wbout], { type: "application/octet-stream" }),
          "仓库情况表.xlsx"
        );
      } catch (e) {
        if (typeof console !== "undefined") {
          console.log(e, wbout);
        }
      }
      return wbout;
    },
    getListId(listId) {
      this.checkIds = listId;
    },
    // 新增
    add() {
      this.ruleForm = {}; 
      this.addDialogVisible = true;
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          insertStore(this.ruleForm).then(res => {
            if (res.Code === 1) {    
              this.$message({
                type: 'success',
                message: '新增成功!'
              })
              this.init();
              this.ruleForm={}
              this.addDialogVisible = false;
            }
          });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },

    // 禁用
    forbidden() {
      if(this.addlist.length>0){
        if(this.addlist[0].IsEnable === 0){
          this.$message('已禁用')
        }else{
          let data = { storeID:this.checkIds[0],isEnable:0}
          startOrStopStore(data).then(res=>{
            if (parseInt(res.Code) === 1) {
              this.$message({
                type: 'success',
                message: '禁用成功!'
              })
              this.init()
            }
          })      
        }        
      }else{
        this.$message('请勾选需要禁用的仓库数据')
      }
    },
    // 启用
    Enable() {
      if(this.addlist.length>0){
        if(this.addlist[0].IsEnable === 1){
          this.$message('已启用')
        }else{
          let data = { storeID:this.checkIds[0],isEnable:1}
          startOrStopStore(data).then(res=>{
            if (parseInt(res.Code) === 1) {
              this.$message({
                type: 'success',
                message: '启用成功!'
              })
              this.init()
            }
          })  
        }     
      }else{
        this.$message('请勾选需要启用的仓库数据')
      }
    },

    changedata(data) {
      this.addlist = data;
    },
    // 修改
    edit(index,row) {
      if (this.addlist.length !== 1) {
        this.$message("请勾选一项");
      }else {
        this.editDialogVisible = true;
        this.editInfo.storeID=this.addlist[0].WareHouseId
        this.editInfo.code=this.addlist[0].Code 
        this.editInfo.storeName=this.addlist[0].Name   
        // this.editInfo.storeType=this.addlist[0].StoreType      
        if(this.addlist[0].WareHouseType==0){
          this.editInfo.storeType="公司总仓"
        }else if(this.addlist[0].WareHouseType==1){
          this.editInfo.storeType="岗位仓"
        }else{
          this.editInfo.storeType="客户仓"
        }
        this.editInfo.fullCapacity=this.addlist[0].FullCapacity
        this.editInfo.isSale=this.addlist[0].IsSale
        this.editInfo.isScheduling=this.addlist[0].IsScheduling
        this.editInfo.isWork=this.addlist[0].IsWork
      }
    },
    editSubmitForm(formName) {
        this.$refs[formName].validate((valid) => {
        if (valid) {
          if(this.editInfo.storeType=="公司总仓"){
            this.editInfo.storeType=0
          }else if(this.editInfo.storeType=="岗位仓"){
            this.editInfo.storeType=1
          }else{
            this.editInfo.storeType=2
          }
          updateStore(this.editInfo).then(res=>{
            if (parseInt(res.Code) === 1) {         
              this.$message({
                type: 'success',
                message: '修改成功'
              })
              this.editDialogVisible = false;
              this.init();
            }
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    
    // 删除   
    remove(){
      if(this.checkIds.length===1){
        this.$confirm('此操作将永久删除选中的仓库数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => { 
          // let data = {storeID:this.checkIds[0]}
          removeStore({storeID:this.addlist[0].WareHouseId}).then(res=>{
            if(parseInt(res.Code) === 1){
              this.$message({
                type: 'success',
                message: '删除成功!' 
              }) 
              this.init()   
            } 
          })            
        }) .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });     
      }else{
        this.$message('请勾选需要删除的仓库数据')
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.sizeBig{
    font-size: 16px;
    margin-left: 20px;
}
.topBtn{
  height: 60px;
  width: 98%;
  margin: 0 auto;
  line-height: 60px;
  display: flex;
  justify-content: space-between;
  .icon-jiny{
    display: inline-block;
    width: 12px;
    height:12px;
    margin-bottom: 2px;
    background: url("image/jinyong.png") no-repeat;
    vertical-align: middle;
  }
  .icon-qiy{
    display: inline-block;
    width: 13px;
    height:13px;
    margin:0 3px 2px 0;
    background: url("image/qiyong.png") no-repeat;
    vertical-align: middle;
  }
}
.message {
  width: 98%;
  margin: 0 auto;
  height: 60px;
  background: rgba(255, 255, 255, 1);
  border: 1px solid rgba(238, 238, 238, 1);
  font-size: 14px;
  .character {
    margin: 20px 0 21px 20px;
    color: #999999;
    .skip {
      color: #0095ff;
      margin-left: 10px;
      cursor: pointer;
    }
  }
}
.inputcontent {
  width: 98%;
  margin: 0 auto;
  height: 80px;
  position: relative;
  padding-top: 21px;
  box-sizing: border-box;
  .iconSearch {
    position: absolute;
    left: 277px;
    top: 30px;
    width: 20px;
    height: 20px;
    background-image: url("image/搜索.png");
    background-repeat: no-repeat;
    cursor: pointer;
  }
  .inSearch {
    width: 308px;
    height: 40px;
  }
}
.tablesize {
  width: 98%;
  // height: 485px;
  margin: 0 auto;
  // border: 1px solid #eeeeee;
  #out-table{
    border: 1px solid #eeeeee;
  }
}
.block {
  text-align: right;
  margin: 50px 20px 0 0;
}
</style>